package com.sanri.tools.modules.mock.l7.websocket.client;

import com.sanri.tools.modules.core.service.SpringUtils;
import com.sanri.tools.modules.mock.l7.websocket.event.*;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

@Slf4j
public class CustomWebsocketClient extends WebSocketClient {

    public CustomWebsocketClient(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        final ConnectWebsocketEvent connectWebsocketEvent = new ConnectWebsocketEvent(this, handshakedata);
        SpringUtils.getApplicationContext().publishEvent(connectWebsocketEvent);
    }

    @Override
    public void onMessage(String message) {
        final WebsocketEvent websocketEvent = new MessageWebsocketEvent(this, message);
        SpringUtils.getApplicationContext().publishEvent(websocketEvent);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        final CloseWebsocketEvent websocketEvent = new CloseWebsocketEvent(this, code,reason, remote);
        SpringUtils.getApplicationContext().publishEvent(websocketEvent);
    }

    @Override
    public void onError(Exception ex) {
        final ErrorWebsocketEvent websocketEvent = new ErrorWebsocketEvent(this, ex);
        SpringUtils.getApplicationContext().publishEvent(websocketEvent);
    }
}
